using ERP.Infeartructure;
using Microsoft.EntityFrameworkCore;
using ERP.Api.Infrastructure.ModelBinding;
using ERP.Api.Infrastructure.Json;
using System.Text.Json.Serialization;

namespace ERP.Api
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllers(options =>
            {
                // MVC ModelBinder：处理表单/QueryString 等来源
                options.ModelBinderProviders.Insert(0, new EmptyStringToNullBinderProvider());
            })
            .AddJsonOptions(opt =>
            {
                // System.Text.Json：处理 [FromBody] JSON 来源
                opt.JsonSerializerOptions.Converters.Add(new NullableDecimalConverter());
                opt.JsonSerializerOptions.Converters.Add(new NullableIntConverter());
                opt.JsonSerializerOptions.Converters.Add(new NullableLongConverter());
                opt.JsonSerializerOptions.Converters.Add(new NullableBoolConverter());
                opt.JsonSerializerOptions.Converters.Add(new NullableDateTimeConverter());
                // 按需：属性名大小写不敏感
                opt.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
            });

            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen(x =>
            {
                var file = Path.Combine(AppContext.BaseDirectory + "ERP.Api.xml");
                x.IncludeXmlComments(file, true);
            }
            );

            // DbContext 注册（MySQL - Pomelo）
            var conn = builder.Configuration.GetConnectionString("DefaultConnection");
            builder.Services.AddDbContext<ErpDbContext>(options =>
                options.UseMySql(conn, ServerVersion.AutoDetect(conn)));

            // CORS：本地联调
            builder.Services.AddCors(options =>
            {
                options.AddDefaultPolicy(policy =>
                    policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
            });

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UseCors();
            app.UseAuthorization();

            app.MapControllers();

            app.Run();
        }
    }
}
